package com.xx.happychatboot.serve.room.service.impl;

import com.xx.happychatboot.base.enums.NormalOrNoEnum;
import com.xx.happychatboot.base.utils.GenerateKeyUtils;
import com.xx.happychatboot.serve.room.domain.entity.GroupMember;
import com.xx.happychatboot.serve.room.domain.entity.RoomFriend;
import com.xx.happychatboot.serve.room.mapper.GroupMemberMapper;
import com.xx.happychatboot.serve.room.mapper.RoomFriendMapper;
import com.xx.happychatboot.serve.room.service.IGroupMemberService;
import com.xx.happychatboot.serve.room.service.IRoomFriendService;
import io.mybatis.service.AbstractService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service
public class RoomFriendServiceImpl extends AbstractService<RoomFriend, Long, RoomFriendMapper> implements IRoomFriendService {
    @Autowired
    private RoomFriendMapper roomFriendMapper;

    /**
     * 根据房间key获取房间信息
     *
     * @param key
     * @return
     */
    @Override
    public RoomFriend getRoomByRoomKey(String key) {
        if (StringUtils.isBlank(key)) {
            throw new RuntimeException("房间key不能为空");
        }
        return roomFriendMapper.getRoomByRoomKey(key);
    }

    /**
     * 恢复房间
     *
     * @param roomFriend
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void restoreRoomIfNeed(RoomFriend roomFriend) {
        if (Objects.equals(roomFriend.getStatus(), NormalOrNoEnum.NOT_NORMAL.getStatus())) {
            roomFriendMapper.restoreRoom(roomFriend.getId());
        }
    }

    /**
     * 创建好友房间
     *
     * @param roomId   房间id
     * @param uid      用户id
     * @param targetId 目标用户id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RoomFriend createFriendRoom(Long roomId, Long uid, Long targetId) {
        if (Objects.isNull(roomId) || Objects.isNull(uid) || Objects.isNull(targetId)) {
            throw new RuntimeException("创建好友房间出现异常，请联系管理员");
        }
        String key = GenerateKeyUtils.generateRoomKey(uid, targetId);
        RoomFriend roomFriend = RoomFriend.buildFriendRoom(roomId, uid, targetId, key);
        roomFriendMapper.insert(roomFriend);
        return roomFriend;
    }
}
